﻿
Namespace PL.MetaSDK 'Processing Layer

    ''' <summary>
    ''' This Class is the Processing layer to manipulate and generate schemas of security based on various 
    ''' data tables such as MetuserIDControlProps, MetuserIDColumns and ListValues etc.
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Class SecurityProfiler_PL
        Public Shared SecurityProfileDS As DataSet = New DataSet("SecurityProfile")
        ''' <summary>
        ''' This will genarate the shema of MetuserIDcolumn for a given User 
        ''' into ......
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GenerateDataFieldSecurity(ByVal userID As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("DataFieldSecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserListValuesByGCCTSSecurity")
                sqlcmd.Parameters("@UserID").Value = userID
                sqlcmd.Parameters("@ListID").Value = DBNull.Value
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function
        ''' <summary>
        ''' This will genarate the shema of MetauserControlprops for a given User 
        ''' into ......
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks>
        ''' 
        ''' 
        ''' Testing Standard Procedure : 
        '''               Use the Master User "sql_RR" value ID : '2f4ff314-937e-4785-92da-3cfc72daf8d8'
        '''               Use the basic English value ID : 'b5fe2d64-7575-4fa8-b19b-d08cd8a11b6f'
        '''               Sql statement: 
        '''                           Execute ssp_MetaUserControlSecurity @UserID = '2f4ff314-937e-4785-92da-3cfc72daf8d8',@LanguageStringID = 'b5fe2d64-7575-4fa8-b19b-d08cd8a11b6f' 
        '''                                                                  								
        ''' </remarks>
        Public Shared Function GenerateDataSubjectSecurity(ByVal userID As Guid, ByVal languageId As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("DataSubjectSecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserControlSecurity")
                sqlcmd.Parameters("@UserID").Value = userID
                sqlcmd.Parameters("@LanguageStringID").Value = languageId
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function
        ''' <summary>
        ''' This will genarate the shema of MetauserGroupList for a given User 
        ''' into ......
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GenerateGroupListSecurity(ByVal userID As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("GroupListSecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserGroupListSecurity")
                sqlcmd.Parameters("@UserID").Value = userID
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function

        Public Shared Function GenerateSiteSecurity(ByVal userID As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("SiteSecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserSiteSecurity")
                sqlcmd.Parameters("@UserID").Value = userID
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function

        Public Shared Function GenerateSocietySecurity(ByVal userID As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("SocietySecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserSocietySecurity")
                sqlcmd.Parameters("@UserID").Value = userID
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function
        ''' <summary>
        ''' 
        ''' </summary>
        ''' <remarks></remarks>
        Public Shared Sub GenerateAllSecurity(ByVal userID As Guid, languageId As Guid)
            SecurityProfileDS = New DataSet("SecurityProfile")
            SecurityProfileDS.Tables.Add(GenerateDataSubjectSecurity(userID, languageId))
            SecurityProfileDS.Tables.Add(GenerateGroupListSecurity(userID))
            SecurityProfileDS.Tables.Add(GenerateDataFieldSecurity(userID))
            SecurityProfileDS.Tables.Add(GenerateUserColumnSecurity(userID, languageId))
            SecurityProfileDS.Tables.Add(GenerateSiteSecurity(userID))
            SecurityProfileDS.Tables.Add(GenerateSocietySecurity(userID))
        End Sub
        Public Shared Sub SaveSecurityProfile(ByVal userID As Guid)
            'Le resultat du DataSet doit etre sauvé dans MetaUser.SecuritySchema
            ' C'est un champ XML... Voir comment le sauver... ou en faire un varchar(max)...
            ' un peut d'exploration a faire
            Dim sqlcmd As SqlCommand = Nothing
            Dim newXml As System.Data.SqlTypes.SqlXml

            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                'GenerateAllSecurity(userID, languageId)
                SecurityProfileDS.WriteXml(securityStream, XmlWriteMode.WriteSchema)
                newXml = New System.Data.SqlTypes.SqlXml(securityStream)
                Try
                    sqlcmd = MetaQuery.GetSPCmdByMetaName("SecurityWriteSQLXML")
                    sqlcmd.Parameters("@UserID").Value = userID
                    sqlcmd.Parameters("@SecuritySchema").Value = newXml
                    sqlcmd.ExecuteNonQuery()
                Catch ex As Exception
                    Throw ex
                Finally
                    If sqlcmd IsNot Nothing Then
                        sqlcmd.Connection.Close()
                        sqlcmd.Dispose()
                    End If
                End Try
            End Using
        End Sub
        Public Shared Sub WriteSecurityProfile(ByVal UserColumnSecurity As String, ByVal DataFieldSecurity As String, ByVal DataSubjectSecurity As String, ByVal SiteSecurity As String, ByVal SocietySecurity As String, ByVal GroupListSecurity As String)
            'Loader le MetaUser.SecuritySchema dans le dataset et l'écrire locale
            'filename = devrait etre serveur+user+bd
            'Via encription
            'ReadSecurityProfileFromDB(AppManager.UserID, filename)
            SecurityProfileDS.Tables("UserColumnSecurity").WriteXml(UserColumnSecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(UserColumnSecurity)

            SecurityProfileDS.Tables("DataFieldSecurity").WriteXml(DataFieldSecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(DataFieldSecurity)

            SecurityProfileDS.Tables("DataSubjectSecurity").WriteXml(DataSubjectSecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(DataSubjectSecurity)

            SecurityProfileDS.Tables("GroupListSecurity").WriteXml(GroupListSecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(GroupListSecurity)

            SecurityProfileDS.Tables("SiteSecurity").WriteXml(SiteSecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(SiteSecurity)

            SecurityProfileDS.Tables("SocietySecurity").WriteXml(SocietySecurity, XmlWriteMode.WriteSchema)
            CommonExt.Utils.FileExt.EncryptTextFileContent(SocietySecurity)


            'SaveSecurityProfile(AppManager.UserID, AppManager.ApplicationOption.LanguageId)
        End Sub

        Public Shared Function ReadDataFieldSecurity(ByVal DataFieldSecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(DataFieldSecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using

            Return True
        End Function

        Public Shared Function ReadUserColumnSecurity(ByVal UserColumnSecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(UserColumnSecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using
            Return True
        End Function

        Public Shared Function ReadDataSubjectSecurity(ByVal DataSubjectSecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(DataSubjectSecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using
            Return True
        End Function

        Public Shared Function ReadGroupListSecurity(ByVal GroupListSecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(GroupListSecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using
            Return True
        End Function

        Public Shared Function ReadSiteSecurity(ByVal SiteSecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(SiteSecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using
            Return True
        End Function

        Public Shared Function ReadSocietySecurity(ByVal SocietySecurity As String) As Boolean

            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc = New System.Xml.XmlDocument
            xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(SocietySecurity))
            Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                xmlDoc.Save(securityStream)
                securityStream.Position = 0
                SecurityProfileDS.BeginInit()
                SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                SecurityProfileDS.EndInit()
            End Using
            Return True
        End Function

        Public Shared Sub ReadSecurityProfile(ByVal UserColumnSecurity As String, ByVal DataFieldSecurity As String, ByVal DataSubjectSecurity As String, ByVal SiteSecurity As String, ByVal SocietySecurity As String)
            'Lire le fichier local.
            'filename = devrait etre serveur+user+bd
            'Via encription

            '' '' '' ''Dim swatch As Stopwatch = New Stopwatch()

            '' '' '' ''SecurityProfileDS = New DataSet("SecurityProfile")

            '' '' '' ''Dim action As Action(Of Object) = Sub(File As Object)
            '' '' '' ''                                      Dim xmlDoc As New System.Xml.XmlDocument
            '' '' '' ''                                      xmlDoc = New System.Xml.XmlDocument
            '' '' '' ''                                      xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(File.ToString))
            '' '' '' ''                                      Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '' '' '' ''                                          xmlDoc.Save(securityStream)
            '' '' '' ''                                          securityStream.Position = 0
            '' '' '' ''                                          SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            '' '' '' ''                                      End Using

            '' '' '' ''                                  End Sub
            '' '' '' ''swatch.Start()

            'Dim t1 As New Task(action, DataFieldSecurity)
            't1.RunSynchronously()


            'Dim t2 As New Task(action, UserColumnSecurity)
            't2.RunSynchronously()


            'Dim t3 As New Task(action, DataSubjectSecurity)
            't3.RunSynchronously()


            'Dim t4 As New Task(action, SiteSecurity)
            't4.RunSynchronously()


            'Dim t5 As New Task(action, SocietySecurity)
            't5.RunSynchronously()
            'Task.WaitAll()
            'Console.WriteLine("time 1 : " + swatch.ElapsedMilliseconds.ToString)

            'swatch.Stop()

            't5.Wait()
            't1.Wait()
            't2.Wait()
            't3.Wait()
            't4.Wait()

            '' '' '' ''Dim t1 = Task(Of Boolean).Factory.StartNew(Function() ReadDataFieldSecurity(DataFieldSecurity))
            '' '' '' ''Dim t2 = Task(Of Boolean).Factory.StartNew(Function() ReadUserColumnSecurity(UserColumnSecurity))
            '' '' '' ''Dim t3 = Task(Of Boolean).Factory.StartNew(Function() ReadDataSubjectSecurity(DataSubjectSecurity))
            '' '' '' ''Dim t4 = Task(Of Boolean).Factory.StartNew(Function() ReadSiteSecurity(SiteSecurity))
            '' '' '' ''Dim t5 = Task(Of Boolean).Factory.StartNew(Function() ReadSocietySecurity(SocietySecurity))

            'Console.WriteLine("t1 {0}", t1.Result)
            'Console.WriteLine("t2 {0}", t2.Result)
            'Console.WriteLine("t3 {0}", t3.Result)
            'Console.WriteLine("t4 {0}", t4.Result)
            'Console.WriteLine("t5 {0}", t5.Result)
            'Console.ReadLine()

            ' '' '' '' ''Console.WriteLine("time 2 : {0} {1} {2} {3} {4} {5} ", t1.Result, t2.Result, t3.Result, t4.Result, t5.Result, swatch.ElapsedMilliseconds)

            ' '' '' '' ''swatch.Stop()

            't1.waith()
            't2.waith()
            't3.waith()
            't4.Waith()
            't5.waith()
            'Parallel.Invoke(New Action(AddressOf ReadDataFieldSecurity(DataFieldSecurity)), New Action(AddressOf PrintCharacters), New Action(AddressOf PrintArray))
            'Console.ReadLine()



            'Dim xmlDoc As New System.Xml.XmlDocument
            'xmlDoc = New System.Xml.XmlDocument
            'xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(DataFieldSecurity))
            'Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '    xmlDoc.Save(securityStream)
            '    securityStream.Position = 0
            '    SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            'End Using

            'xmlDoc = New System.Xml.XmlDocument
            'xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(UserColumnSecurity))
            'Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '    xmlDoc.Save(securityStream)
            '    securityStream.Position = 0
            '    SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            'End Using

            'xmlDoc = New System.Xml.XmlDocument
            'xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(DataSubjectSecurity))
            'Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '    xmlDoc.Save(securityStream)
            '    securityStream.Position = 0
            '    SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            'End Using

            'xmlDoc = New System.Xml.XmlDocument
            'xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(SiteSecurity))
            'Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '    xmlDoc.Save(securityStream)
            '    securityStream.Position = 0
            '    SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            'End Using

            'xmlDoc = New System.Xml.XmlDocument
            'xmlDoc.LoadXml(CommonExt.Utils.FileExt.DecryptTextFileContent(SocietySecurity))
            'Using securityStream As IO.MemoryStream = New IO.MemoryStream()
            '    xmlDoc.Save(securityStream)
            '    securityStream.Position = 0
            '    SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
            'End Using

        End Sub

        Public Shared Sub ReadSecurityProfileFromDB(ByVal userID As Guid, ByVal filename As String)
            'Lire le MetaUser.SecuritySchema. Et le Mettre dans le DataSet
            'SecurityProfileDS.LoadXml(filename)
            Dim xmlDoc As New System.Xml.XmlDocument
            Using mq As MetaQuery = MetaQuery.GetMetaQueryByName("SecurityReadSQLXML")
                mq.SQLWhere = String.Format("UserID = '{0}'", userID)
                mq.FillResultQuery()
                If Not IsNothing(mq.ResultQuery.Rows(0).Item("SecuritySchema")) Then
                    If Not IsDBNull(mq.ResultQuery.Rows(0).Item("SecuritySchema")) Then
                        Using securityStream As IO.MemoryStream = New IO.MemoryStream()
                            SecurityProfileDS = New DataSet("SecurityProfile")
                            xmlDoc.LoadXml(mq.ResultQuery.Rows(0).Item("SecuritySchema"))
                            xmlDoc.Save(securityStream)
                            securityStream.Position = 0
                            SecurityProfileDS.BeginInit()
                            SecurityProfileDS.ReadXml(securityStream, XmlReadMode.ReadSchema)
                            SecurityProfileDS.EndInit()
                        End Using
                    End If
                End If
            End Using
        End Sub

        ''' <summary>
        ''' </summary>
        ''' <param name="userID"></param>
        ''' <param name="languageId"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GenerateUserColumnSecurity(ByVal userID As Guid, ByVal languageId As Guid) As DataTable
            Dim sqlcmd As SqlCommand = Nothing
            Dim result As New DataTable("UserColumnSecurity")
            '
            Try
                sqlcmd = MetaQuery.GetSPCmdByMetaName("SSPMetaUserColumnsSecurity")
                sqlcmd.Parameters("@QueryName").Value = DBNull.Value
                sqlcmd.Parameters("@UserID").Value = userID
                sqlcmd.Parameters("@LayoutID").Value = IdRepository.METALAYOUTS_DEFAULT
                sqlcmd.Parameters("@LanguageStringID").Value = languageId
                result.BeginLoadData()
                result.Load(sqlcmd.ExecuteReader(CommandBehavior.CloseConnection))
                result.EndLoadData()
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
            Return result
        End Function
    End Class
End Namespace
